package com.dycong.common.mybatis.handler;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static org.apache.commons.lang3.CharEncoding.UTF_8;

@Slf4j
public class ColumnLengthControlHandler implements TypeHandler<String> {

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, String t, JdbcType jdbcType) throws SQLException {
        if(t == null){
            //空数据，不要加密
            preparedStatement.setString(i, null);
        }else{
            log.info("setParameter encode t={}",t);
            preparedStatement.setString(i, encodingString(t));
        }
    }

    @Override
    public String getResult(ResultSet resultSet, String s) throws SQLException {
        String value = resultSet.getString(s);
        value = decodingString(value);
        log.info("getResult decode t={}",value);
        return value;
    }

    @Override
    public String getResult(ResultSet resultSet, int i) throws SQLException {
        String value = resultSet.getString(i);
        value =  decodingString(value);
        log.info("getResult decode t={}",value);
        return value;
    }

    @Override
    public String getResult(CallableStatement callableStatement, int i) throws SQLException {
        String value = callableStatement.getString(i);
        value = decodingString(value);
        log.info("getResult decode t={}",value);
        return value;
    }

    private String encodingString(String data){
        String str = "";
        try {
            str = StringUtils.isBlank(data) ? "" : URLEncoder.encode(data,UTF_8);
        } catch (UnsupportedEncodingException e) {
            log.error("encodingString error !,data={}", data);
        }
        return str;
    }

    private String decodingString(String data){
        String str = "";
        try {
            str = StringUtils.isBlank(data) ? "" : URLDecoder.decode(URLDecoder.decode(data,UTF_8),UTF_8);
        } catch (UnsupportedEncodingException e) {
            log.error("decodingString error !,data={}", data);
        }
        return str;
    }

}
